package org.springframework.security.authentication;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.context.MessageSource;
import org.springframework.context.MessageSourceAware;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.security.core.SpringSecurityMessageSource;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsChecker;
import org.springframework.util.Assert;

/**
 * @author Dillon
 * @date 2024/7/11
 * @slogan 致敬大师 致敬未来的你
 * @desc 用户账号校验工具类  默认校验 是否过期 是否禁用 是否上锁 凭证是否过期
 */
public class AccountStatusUserDetailsChecker implements UserDetailsChecker, MessageSourceAware {

	/**
	 * 日志对象
	 */
	private final Log logger = LogFactory.getLog(getClass());

	/**
	 * 国际化消息
	 */
	protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();

	/**
	 * 执行校验
	 *
	 * @param user 待校验实现类
	 */
	@Override
	public void check(UserDetails user) {
		if (!user.isAccountNonLocked()) {
			this.logger.debug("用户账号已锁");
			throw new LockedException(this.messages.getMessage("AccountStatusUserDetailsChecker.locked", "用户账号已锁"));
		}
		if (!user.isEnabled()) {
			this.logger.debug("用户账号禁止");
			throw new DisabledException(this.messages.getMessage("AccountStatusUserDetailsChecker.disabled", "用户账号禁止"));
		}
		if (!user.isAccountNonExpired()) {
			this.logger.debug("用户账户过期");
			throw new AccountExpiredException(this.messages.getMessage("AccountStatusUserDetailsChecker.expired", "用户账户过期"));
		}
		if (!user.isCredentialsNonExpired()) {
			this.logger.debug("用户凭证过期");
			throw new CredentialsExpiredException(this.messages.getMessage("AccountStatusUserDetailsChecker.credentialsExpired", "用户凭证过期"));
		}
	}

	/**
	 * 国际化消息实现类
	 *
	 * @param messageSource
	 */
	@Override
	public void setMessageSource(MessageSource messageSource) {
		Assert.notNull(messageSource, "消息不能为空");
		this.messages = new MessageSourceAccessor(messageSource);
	}

}
